package cn.iocoder.yudao.module.trade.framework;

import cn.iocoder.yudao.module.api.trade.delivery.ExpressApi;
import cn.iocoder.yudao.module.api.trade.delivery.ExpressApiFactory;
import cn.iocoder.yudao.module.trade.delivery.api.ExpressApiFactoryImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.http.client.ClientHttpRequestFactorySettings;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

/**
 * 快递接口端配置类：
 * 1. 快递接口工厂 {@link ExpressApiFactory}
 * 2. 默认的快递接口实现 {@link ExpressApi}
 *
 * @author jason
 */
@EnableConfigurationProperties(ExpressApiProperties.class)
@Configuration(proxyBeanMethods = false)
public class ExpressApiConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public RestTemplate restTemplate() {
        return new RestTemplateBuilder()
                .connectTimeout(Duration.ofSeconds(5))
                .readTimeout(Duration.ofSeconds(5))
                .redirects(ClientHttpRequestFactorySettings.Redirects.FOLLOW_WHEN_POSSIBLE)
                .build();
    }

    @Bean
    public ExpressApiFactory expressApiFactory(ExpressApiProperties expressApiProperties, RestTemplate restTemplate) {
        return new ExpressApiFactoryImpl(expressApiProperties, restTemplate);
    }

    @Bean
    public ExpressApi defaultExpressApi(ExpressApiFactory expressApiFactory) {
        return expressApiFactory.getDefaultExpressApi();
    }

}
